﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using System.Threading;
using NHibernate.Cfg;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace cmsservice.DAL.Hibernate
{
    public class DataContext:IDisposable
    {
        ISessionFactory factory = null;
        private static Mutex  m_mutex = new Mutex();

        public ISession Session
        {
            get;
            set;
        }

        private string hibernateConfig;

        public DataContext(string hibernateConfig, ref ISessionFactory sessionFactory)
        {
            this.hibernateConfig=hibernateConfig;
            if (sessionFactory != null)
            {
                this.factory = sessionFactory;
            }
            Session = CreateSession();
            if (sessionFactory == null)
            {
                sessionFactory = factory;
            }
        }

        void InitData()
        {
            if (factory == null)
            {
                m_mutex.WaitOne();
                try
                {
                    string path = System.AppDomain.CurrentDomain.BaseDirectory + "App_Data/" + hibernateConfig;
                    if (!File.Exists(path))
                    {
                        path = System.AppDomain.CurrentDomain.BaseDirectory + hibernateConfig;
                    }
                    Configuration cfg = new Configuration().Configure(path);
                    var c = cfg.BuildSessionFactory();
                    factory = c;
                }
                catch(Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    m_mutex.ReleaseMutex();
                }

            }
        }

        ISession CreateSession()
        {
            InitData();
            return factory.OpenSession();
        }

        ISession CreateSession(IDbConnection con)
        {
            InitData();
            return factory.OpenSession(con);
        }


        public void Dispose()
        {
            try
            {
                Session.Dispose();
            }
            catch
            {
            }
        }
    }

}
